﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace Adams.Web.Data.Events
{
    public static class Occurance
    {
        public static Adams.Web.Models.Events.Occurance.PageLoad PageLoad(int id)
        {
            var data = new Adams.Web.Models.Events.Occurance.PageLoad();

            using (SqlDataReader dr = DB.RunDataReader(@"
DECLARE @EventID int
DECLARE @CalendarID int
SELECT @EventID = EventID FROM Events.Occurances WHERE OccuranceID = @OccuranceID
SELECT @CalendarID = CalendarID FROM Events.Events WHERE EventID = @EventID

SELECT O.*
FROM Events.Occurances O
WHERE O.OccuranceID = @OccuranceID

SELECT E.*
FROM Events.Events E
WHERE E.EventID = @EventID

SELECT C.*
FROM Events.Calendars C
WHERE C.CalendarID = @CalendarID
", CommandType.Text,
    DB.CreateParameter("@OccuranceID", id)))
            {
                if (dr.HasRows)
                {
                    dr.Read();
                    data.Occurance = DB.InitFromReader<Shared.Entities.Events.Occurance>(dr, new ColMap { NameInDb = "OccuranceID", NameInObject = "ID" });

                    dr.NextResult();
                    dr.Read();
                    data.Occurance.Event = DB.InitFromReader<Shared.Entities.Events.Event>(dr, new ColMap { NameInDb = "EventID", NameInObject = "ID" });

                    dr.NextResult();
                    dr.Read();
                    data.Occurance.Event.Calendar = DB.InitFromReader<Shared.Entities.Events.Calendar>(dr, new ColMap { NameInDb = "CalendarID", NameInObject = "ID" });
                }
            }

            return data;
        }
    }
}